<template>
  <div class="code-editor-container" ref="editorContainer">
    <textarea
      ref="textareaRef"
      v-model="innerValue"
      class="code-textarea"
      :placeholder="placeholder"
      @input="handleInput"
      @scroll="syncScroll"
      @keydown="handleKeyDown"
      @click="updateHighlight"
      @select="updateHighlight"
    ></textarea>
    <pre 
      ref="highlightRef" 
      class="code-highlight"
      @scroll="syncScroll"
    ><code :class="language" v-html="highlightedCode"></code></pre>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick, computed } from 'vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs.css' // 导入默认样式

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'cpp'
  },
  placeholder: {
    type: String,
    default: '请输入代码...'
  },
  theme: {
    type: String,
    default: 'vs'
  },
  options: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const innerValue = ref(props.modelValue || '')
const textareaRef = ref<HTMLTextAreaElement | null>(null)
const highlightRef = ref<HTMLPreElement | null>(null)
const editorContainer = ref<HTMLDivElement | null>(null)
const highlightedCode = ref('')

// 处理代码高亮
const updateHighlight = () => {
  if (!innerValue.value) {
    highlightedCode.value = ''
    return
  }
  
  highlightedCode.value = hljs.highlight(
    innerValue.value,
    { language: props.language }
  ).value
}

// 同步滚动
const syncScroll = (e: Event) => {
  const target = e.target as HTMLElement
  const isTextarea = target === textareaRef.value
  const scrollElement = isTextarea ? highlightRef.value : textareaRef.value
  
  if (scrollElement) {
    scrollElement.scrollTop = target.scrollTop
    scrollElement.scrollLeft = target.scrollLeft
  }
}

// 处理输入
const handleInput = () => {
  emit('update:modelValue', innerValue.value)
  emit('change', innerValue.value)
  updateHighlight()
}

// 处理特殊按键
const handleKeyDown = (e: KeyboardEvent) => {
  // Tab键处理
  if (e.key === 'Tab') {
    e.preventDefault()
    const textarea = textareaRef.value
    if (!textarea) return
    
    const start = textarea.selectionStart
    const end = textarea.selectionEnd
    
    // 在光标位置插入两个空格
    innerValue.value = 
      innerValue.value.substring(0, start) + 
      '  ' + 
      innerValue.value.substring(end)
    
    // 移动光标到插入后的位置
    nextTick(() => {
      textarea.selectionStart = textarea.selectionEnd = start + 2
      updateHighlight()
    })
  }
}

// 监听值变化
watch(() => props.modelValue, (newVal) => {
  if (newVal !== innerValue.value) {
    innerValue.value = newVal || ''
    updateHighlight()
  }
})

// 监听语言变化
watch(() => props.language, () => {
  updateHighlight()
})

// 组件挂载后初始化高亮
onMounted(() => {
  updateHighlight()
  
  // 解决编辑器外部点击问题
  document.addEventListener('mousedown', (e) => {
    if (editorContainer.value && !editorContainer.value.contains(e.target as Node)) {
      // 点击在编辑器外部，移除焦点
      if (textareaRef.value) {
        textareaRef.value.blur()
      }
    }
  })
})
</script>

<style scoped>
.code-editor-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
}

.code-textarea,
.code-highlight {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 10px;
  margin: 0;
  border: none;
  box-sizing: border-box;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre;
  overflow: auto;
}

.code-textarea {
  color: transparent;
  background: transparent;
  caret-color: #333;
  resize: none;
  z-index: 2;
  /* 关键修复：确保透明文本但可见的光标 */
  -webkit-text-fill-color: transparent;
  tab-size: 2;
}

.code-highlight {
  z-index: 1;
  pointer-events: none;
  /* 重要：与textarea完全一致的样式 */
  padding: 10px;
  margin: 0;
  white-space: pre;
  overflow: auto;
  /* 防止影响文本选择 */
  user-select: none;
}

.code-highlight code {
  display: block;
  font-family: inherit;
  white-space: inherit;
  overflow: visible;
  tab-size: 2;
}

/* 修复文本选择问题 */
::selection {
  background: rgba(0, 0, 255, 0.2);
}
::-moz-selection {
  background: rgba(0, 0, 255, 0.2);
}

/* 适配深色主题 */
.dark .code-editor-container {
  border-color: #4c4d4f;
  background-color: #1e1e1e;
}

.dark .code-textarea {
  caret-color: #fff;
}
</style> 